package com.du.ichat.utils;

import com.du.ichat.bean.Contact;
import com.netease.nimlib.sdk.uinfo.model.NimUserInfo;

import net.sourceforge.pinyin4j.format.HanyuPinyinCaseType;
import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;
import net.sourceforge.pinyin4j.format.HanyuPinyinToneType;

import java.text.Collator;
import java.util.Comparator;
import java.util.Locale;

public class ContactComparer implements Comparator<NimUserInfo> {
    private Comparator<Object> CHINA_COMPARE = Collator.getInstance(Locale.ENGLISH);
    private static HanyuPinyinOutputFormat format = new HanyuPinyinOutputFormat();
    public ContactComparer() {
        format.setCaseType(HanyuPinyinCaseType.UPPERCASE);
        format.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
    }

    @Override
    public int compare(NimUserInfo o1, NimUserInfo o2) {
        if(getLetter(o1).equals("#") || getLetter(o2).equals("#") ){
            if(getLetter(o1).equals("#") && getLetter(o2).equals("#") ){
                return 1;
            }
            if(getLetter(o1).equals("#")  ){
                return 1;
            }
            if(getLetter(o2).equals("#")  ){
                return -1;
            }
        }
        String pingyin1 = PinYinUtils.getPinyinString(o1.getName());
        String pingyin2 = PinYinUtils.getPinyinString(o2.getName());
        return CHINA_COMPARE.compare(pingyin1 , pingyin2);
    }


    private String getLetter(NimUserInfo userinfo) {
        String name = userinfo.getName();
        String letter = PinYinUtils.getFirstSpell(name);
        if(letter.charAt(0) >='A'){
            if(letter.charAt(0) <='Z'){
                return letter;
            }
        }
        return "#";
    }

}
